<template>
  <div class="app-container">
      <!-- <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="监控编号" prop="cameraIndexCode">
              <el-input v-model="queryParams.cameraIndexCode" placeholder="请输入监控编号" clearable
                  @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
      </el-form> -->

      <el-row :gutter="10" class="mb8">
          <!-- <el-col :span="1.5">
              <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                  v-hasPermi="['wanzhi:cameraConfig:add']">新增</el-button>
          </el-col> -->
          <el-col :span="1.5">
              <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                  v-hasPermi="['wanzhi:cameraConfig:edit']">修改</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
              <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
                  v-hasPermi="['wanzhi:cameraConfig:remove']">删除</el-button>
          </el-col> -->
          <el-col :span="1.5">
              <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                  v-hasPermi="['wanzhi:cameraConfig:export']">导出</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="cameraConfigList" @selection-change="handleSelectionChange"
          :row-key="record => record.id">
          <el-table-column type="selection" width="55" align="center" />
          <!-- <el-table-column label="序号" align="center" prop="id" /> -->
          <el-table-column label="序号" align="center" prop="sortNum" />
          <el-table-column label="类型" align="center" prop="type" />
          <el-table-column label="监控" align="center" prop="cameraIndexCode">
              <template slot-scope="scope">
                  <el-button type="text" size="small" icon="el-icon-view" @click="handlePreview(scope.row)">查看</el-button>
              </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                  <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                      v-hasPermi="['wanzhi:cameraConfig:edit']">修改</el-button>
                  <!-- <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                      v-hasPermi="['wanzhi:cameraConfig:remove']">删除</el-button> -->
              </template>
          </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
          @pagination="getList" />

      <!-- 添加或修改监控视频配置对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">
              <el-form-item label="监控编号" prop="cameraIndexCode">
                  <el-input v-model="form.cameraIndexCode" placeholder="请输入监控编号" />
              </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="submitForm">确 定</el-button>
              <el-button @click="cancel">取 消</el-button>
          </div>
      </el-dialog>

      <el-dialog title="修改监控" :visible.sync="videoOpen" width="600px" append-to-body>
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">
              <el-form-item label="序号" prop="sortNum">
                  <el-input-number v-model.trim="form.sortNum" controls-position="right" placeholder="请输入序号" :min="1"
                      :max="100000000"></el-input-number>
              </el-form-item>
          </el-form>
          <div style="width: 100%;height: 450px;overflow: hidden; overflow-y: auto;">
              <el-tree :data="regionOptions" :props="defaultProps" :expand-on-click-node="false"
                  :filter-node-method="filterNode" ref="tree" node-key="indexCode" highlight-current :load="loadNode" lazy
                  :default-expanded-keys="['root00000000']">
                  <span class="custom-tree-node" slot-scope="{ node, data }">
                      <div v-if="data.cameraIndexCode">
                          <el-radio v-model="videoCheckedStr" :label="data.cameraIndexCode" name="cameraIndexCode"
                              style="margin: 0 5px;" @change="handleVideoChange(data)">
                              <span @click="handleNodeClick(data)">{{ data.name }}</span>
                          </el-radio>
                      </div>
                      <span v-if="!data.cameraIndexCode">{{ `${data.name}` }}</span>
                  </span>
              </el-tree>
          </div>
          <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="submitVideoForm" :loading="submitVideoLoading">确 定</el-button>
              <el-button @click="cancelVideoForm">取 消</el-button>
          </div>
      </el-dialog>

      <el-dialog title="查看监控" :visible.sync="openVideoVisible" @close="handleCloseLive" width="700px" append-to-body
          :destroy-on-close="true">
          <div v-if="showVideo" :key="currentVideoCode">
              <LivePlayer :key="currentVideoCode" :videoUrl="sourceUrls" fluent autoplay live></LivePlayer>
          </div>
      </el-dialog>
  </div>
</template>

<script>
import { listCameraConfig, getCameraConfig, delCameraConfig, addCameraConfig, updateCameraConfig } from "@/api/wanzhi/cameraConfig";
import axios from 'axios';
import LivePlayer from "@liveqing/liveplayer";
import { Message } from 'element-ui'

const HK_API_URL = process.env.VUE_APP_BASE_VIDEO;

export default {
  name: "CameraConfig",
  components: {
      LivePlayer,
  },
  data() {
      return {
          // 遮罩层
          loading: true,
          // 选中数组
          ids: [],
          // 非单个禁用
          single: true,
          // 非多个禁用
          multiple: true,
          // 显示搜索条件
          showSearch: true,
          // 总条数
          total: 0,
          // 监控视频配置表格数据
          cameraConfigList: [],
          // 弹出层标题
          title: "",
          // 是否显示弹出层
          open: false,
          // 查询参数
          queryParams: {
              pageNum: 1,
              pageSize: 10,
              type: '城管',
              cameraIndexCode: null,
          },
          // 表单参数
          form: {},
          // 表单校验
          rules: {
          },
          // 组织树选项
          regionOptions: undefined,
          defaultProps: {
              children: "children",
              label: "name",
              isLeaf: 'leaf',
          },
          videoOpen: false,
          loadingVideo: false,
          sourceUrls: '',
          openVideoVisible: false,
          videoCheckedStr: '',
          submitVideoLoading: false,
          previewLoading: false,
          currentVideoCode: '',
          showVideo: true,
      };
  },
  created() {
      this.getList();
  },
  methods: {
      /** 查询监控视频配置列表 */
      getList() {
          this.loading = true;
          listCameraConfig(this.queryParams).then(response => {
              this.cameraConfigList = response.rows;
              this.total = response.total;
              this.loading = false;
          });
      },
      // 取消按钮
      cancel() {
          this.open = false;
          this.reset();
      },
      // 表单重置
      reset() {
          this.form = {
              id: null,
              type: null,
              cameraIndexCode: null,
              createTime: null,
              updateTime: null
          };
          this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
          this.queryParams.pageNum = 1;
          this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
          this.resetForm("queryForm");
          this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
          this.ids = selection.map(item => item.id)
          this.single = selection.length !== 1
          this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
          this.reset();
          this.open = true;
          this.title = "添加监控视频配置";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
          // this.reset();
          const id = row.id || this.ids
          getCameraConfig(id).then(response => {
              this.form = response.data;
              this.videoOpen = true
              this.videoCheckedStr = row.cameraIndexCode;
              this.getRegionTree();
          });
      },
      /** 提交按钮 */
      submitForm() {
          this.$refs["form"].validate(valid => {
              if (valid) {
                  if (this.form.id != null) {
                      this.form.type = '城管'
                      updateCameraConfig(this.form).then(response => {
                          this.$modal.msgSuccess("修改成功");
                          this.open = false;
                          this.getList();
                      });
                  } else {
                      this.form.type = '城管'
                      addCameraConfig(this.form).then(response => {
                          this.$modal.msgSuccess("新增成功");
                          this.open = false;
                          this.getList();
                      });
                  }
              }
          });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
          const ids = row.id || this.ids;
          this.$modal.confirm('是否确认删除监控视频配置编号为"' + ids + '"的数据项？').then(function () {
              return delCameraConfig(ids);
          }).then(() => {
              this.getList();
              this.$modal.msgSuccess("删除成功");
          }).catch(() => { });
      },
      /** 导出按钮操作 */
      handleExport() {
          this.download('wanzhi/cameraConfig/export', {
              ...this.queryParams
          }, `cameraConfig_${new Date().getTime()}.xlsx`)
      },
      /** 查询部门下拉树结构 */
      getRegionTree() {
          axios({
              url: HK_API_URL + "/hk/getRegionTree",
              method: "GET",
              params: {
                  indexCode: 'root00000000',
                  t: Date.now(),
              }
          }).then(result => {
              if (result.status == 200) {
                  this.regionOptions = result.data;
              } else {
                  Message.error('请求失败')
              }
          })
      },
      // 节点load事件
      loadNode(node, resolve) {
          const data = node?.data || [];
          if (node.level === 0) {
              return resolve([{ name: "湾沚区" }]);
          }
          // this.queryParams.indexCode = data.indexCode;
          if (data?.children && data.children.length > 0) {
              setTimeout(() => {
                  const child = data.children
                  resolve(child);
              }, 500)
          }
          if (data?.children && data.children.length == 0 && data.is_last == 1) {
              axios({
                  url: HK_API_URL + "/hk/getCameraListByCode",
                  method: "GET",
                  params: {
                      unitIndexCode: data.indexCode,
                      t: Date.now(),
                  }
              }).then(result => {
                  if (result.status == 200) {
                      const res = result.data.map(item => {
                          return {
                              ...item,
                              leaf: true
                          }
                      })
                      resolve(res);
                  } else {
                      Message.error('请求失败')
                  }
              })
          }
          resolve([]);

          // this.handleQuery();
      },
      // 节点单击事件
      handleNodeClick(data) {
          if (this.previewLoading) return;
          this.currentVideoCode = data?.cameraIndexCode;
          if (data?.cameraIndexCode) {
              const params = new FormData();
              params.append('cameraIndexCode', data?.cameraIndexCode)
              params.append('expand', 'transcode=1')
              params.append('protocol', 'hls')
              params.append('streamType', 1)
              params.append('transmode', 0)
              params.append('t', Date.now())

              this.previewLoading = true;
              axios.post(HK_API_URL + "/hk/previewURLsByCode", params, {
                  headers: {
                      'content-type': 'application/json;charset=UTF-8'
                  },
              }).then(result => {
                  if (result.status == 200) {
                      if(!result?.data?.data?.url){
                          this.previewLoading = false;
                          Message.error('请求失败')
                          return;
                      }
                      this.openVideoVisible = true;
                      this.loadingVideo = false;
                      this.previewLoading = false;
                      this.showVideo = true

                      setTimeout(() => {
                          this.sourceUrls = result?.data?.data?.url + `?t=${Date.now()}` || '';
                      }, 50)
                  } else {
                      this.sourceUrls = ''
                      this.previewLoading = false;
                      Message.error('请求失败')
                  }
              }).catch(e => {
                  Message.error('请求失败')
              })
          } else {
              Message.error('预览失败')
          }
      },
      // 筛选节点
      filterNode(value, data) {
          if (!value) return true;
          return data.name.indexOf(value) !== -1;
      },
      // 修改视频code
      submitVideoForm() {
          const param = {
              ...this.form,
              cameraIndexCode: this.videoCheckedStr
          }
          this.submitVideoLoading = true
          updateCameraConfig(param).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.submitVideoLoading = false
              this.videoOpen = false;
              this.getList();
          });
      },
      cancelVideoForm() {
          this.videoOpen = false;
          this.previewLoading = false;
      },
      // 预览视频
      handlePreview(data) {
          this.handleNodeClick(data)
      },
      // 关闭查看监控弹窗
      handleCloseLive() {
          this.previewLoading = false;
          this.currentVideoCode = '';
          this.showVideo = false
          setTimeout(() => {
              this.sourceUrls = ''
          }, 50)
      },
      // 视频监控切换
      handleVideoChange(data) {
          this.form.remark = data.name
      }
  }
};
</script>
